﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace mal.balades.Business.Helper
{
    public class GpsHelper
    {
        /// <summary>
        /// Gets the distance in kilometers between two points
        /// </summary>       
        public static double GetDistance(double latitude1, double longitude1, double latitude2, double longitude2)
        {
            double a = Math.PI / 180; 
            double lat1 = latitude1 * a; 
            double lat2 = latitude2 * a; 
            double lon1 = longitude1 * a; 
            double lon2 = longitude2 * a;
            double t1 = Math.Sin(lat1) * Math.Sin(lat2); 
            double t2 = Math.Cos(lat1) * Math.Cos(lat2);
            double t3 = Math.Cos(lon1 - lon2); 
            double t4 = t2 * t3; 
            double t5 = t1 + t4;
            double rad_dist = Math.Atan(-t5/Math.Sqrt(-t5 * t5 +1)) + 2 * Math.Atan(1);
            
            return (rad_dist * 3437.74677 * 1.1508) * 1.6093470878864446;
        }

        public enum CoordinateType { longitude, latitude };

        public static string DecimalDegreesDtoDegreesMinutesSecondes(double coordinate, CoordinateType type)
        {
            // Set flag if number is negative
            bool neg = coordinate < 0d;

            // Work with a positive number
            coordinate = Math.Abs(coordinate);

            // Get d/m/s components
            double d = Math.Floor(coordinate);
            coordinate -= d;
            coordinate *= 60;
            double m = Math.Floor(coordinate);
            coordinate -= m;
            coordinate *= 60;
            double s = Math.Round(coordinate);

            // Create padding character
            char pad;
            char.TryParse("0", out pad);

            // Create d/m/s strings
            string dd = d.ToString();
            string mm = m.ToString().PadLeft(2, pad);
            string ss = s.ToString().PadLeft(2, pad);

            // Append d/m/s
            string dms = string.Format("{0}°{1}'{2}\"", dd, mm, ss);

            // Append compass heading
            switch (type)
            {
                case CoordinateType.longitude:
                    dms += neg ? "W" : "E";
                    break;
                case CoordinateType.latitude:
                    dms += neg ? "S" : "N";
                    break;
            }

            // Return formated string
            return dms;
        }
    }
}
